<template>
  <div>
    <el-breadcrumb separator="/" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/admin/user/list">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb><br><br>

    &nbsp;&nbsp;
    账号：
    <el-input placeholder="请输入账号" v-model="input.username" clearable @input="listUsersByCondition()" style="width: 200px;"></el-input>
    &nbsp;&nbsp;
    昵称：
    <el-input placeholder="请输入昵称" v-model="input.nick" clearable @input="listUsersByCondition()"
              style="width: 200px;"></el-input>
    &nbsp;&nbsp;
    手机号：
    <el-input placeholder="请输入手机号" v-model="input.phone" clearable change @input="listUsersByCondition()"
              style="width: 200px;"></el-input>
    &nbsp;
    <!--按钮：搜索-->
    <!--    <el-button type="primary" icon="el-icon-search" @click="listUsersByCondition()">搜索</el-button>-->

    <!--按钮：角色状态-->
    <el-dropdown>
      <el-button type="primary" style="margin-left: 10px">{{ usernameStatus }}</el-button>
      <el-dropdown-menu slot="dropdown">
        <a href="javascript:void(0)" @click="queryStatus(1)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>正常使用</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryStatus(2)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>禁用状态</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryStatus(3)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>全部状态</el-dropdown-item>
        </a>
      </el-dropdown-menu>
    </el-dropdown>


    &nbsp;&nbsp;
    <!--按钮：创建用户-->
    <!--    <el-button type="primary" @click="cardPopup(0)" style="margin: 0 0 15px 0">创建</el-button>-->
    <!--    -->

    <!--按钮：批量删除-->
    <el-button type="danger" @click="handleDeleteList()">批量删除</el-button>


    <br><br>


    <!--用户列表-->
    <template>
      <el-table
          :data="tableData"
          ref="multipleTable"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="40">
        </el-table-column>
        <el-table-column fixed prop="id" label="ID" width="70"></el-table-column>
        <el-table-column fixed prop="avatar" label="头像" width="100">
          <template slot-scope="scope">
            <el-avatar
                :size="80"
                :src="scope.row.avatar"
            ></el-avatar>
          </template>
        </el-table-column>
        <!--        <el-table-column fixed prop="avatar" label="头像" width="130"></el-table-column>-->
        <el-table-column fixed prop="nick" label="用户昵称" width="100"></el-table-column>
        <el-table-column fixed prop="username" label="用户账号" width="100"></el-table-column>
        <el-table-column fixed prop="phone" label="电话" width="110"></el-table-column>
        <el-table-column fixed prop="commentCount" label="评论数" width="70"></el-table-column>
        <el-table-column fixed prop="pointedCount" label="被赞量" width="70"></el-table-column>
        <el-table-column fixed prop="collectCount" label="收藏量" width="70"></el-table-column>
        <el-table-column fixed prop="beanCount" label="粉丝量" width="70"></el-table-column>
        <el-table-column fixed prop="lastLogin" label="最后登录时间" width="155"></el-table-column>
        <el-table-column fixed prop="status" label="账号状态" width="80">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.status==1?'已启用':'已禁用'">
              <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inacti
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleEdit(scope.row)">
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="140"
        >
          <template slot-scope="scope">

              <el-button type="primary" icon="el-icon-s-grid" circle
                         @click="drawer = true;
                          menuPopups();userRoleEcho(scope.row.id)
                        "></el-button>
              <el-button type="danger" icon="el-icon-delete" circle
                         @click="handleDelete(scope.row)"></el-button>

          </template>
        </el-table-column>
      </el-table>
    </template>


    <!--分配角色-->
    <template>
      <el-drawer
          title="分配角色"
          append-to-body
          :before-close="handleClose"
          :visible.sync="drawer"
          direction="rtl"
          custom-class="demo-drawer"
          ref="drawer"
      >
        <div class="demo-drawer__content">
          <el-form ref="ruleForm" label-width="180px" class="demo-ruleForm">
            <el-tree
                :data="treeData"
                ref="tree"
                show-checkbox
                node-key="key"
                :default-expanded-keys = [0]
                :default-checked-keys = optionsSelectEcho
                style="bottom: -10px"
                :props="defaultProps"
            />
          </el-form>
          <div class="demo-drawer__footer" style="position: relative;top: 30px;">
            <el-button @click="cancelForm">取 消</el-button>
                <el-button
                    type="primary"
                    @click="handleCloses()"
                    >提 交
                </el-button>
          </div>
        </div>
      </el-drawer>
    </template>


    <!--页码-->
    <template>
      <div>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 7, 10, 20]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="countDate">
        </el-pagination>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {

      ruleForm: {
        id: '',
        username: '',
        password: '',
        avatar: '',
        nick: '',
        gender: 1,
        phone: '',
        lastLogin: '',
        signature: '',
        status: 1,
        optionsSelect: [],
      },       // 添加 / 修改数据集
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
        ],
        nick: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 11, max: 11, message: '长度为11个字符', trigger: 'blur'}
        ],
      },                // 输入验证
      input: {
        username: '',
        nick: '',
        phone: '',
        status: 1,
        pageNum: '',
        pageSize: ''
      },    // 查询条件集

      treeData: [],            // 权限树数据源
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      optionsSelectEcho:[],    // 角色权限回填数组

      usernameStatus: '正常使用',       // 用户状态筛选---【首页筛选用户状态按钮】

      tableData: [],           // 条件查询结果集
      multipleSelection: [],   // 批量删除复选框

      roleStatus: '正常使用',   // 按钮：角色状态筛选的名称
      AddOrSetByRoleId: 0,    // 区别方法【添加 ro 修改】
      dialogVisible: false,   // 弹出框状态(添加 or 修改功能)，默认隐藏
      dialogVisibleTitle: '添加用户',   // 弹框标题---【添加 or 修改功能】
      drawer: false,          // 弹出框状态(权限树列表)，默认隐藏
      props: {multiple: true},// 默认弹窗的默认设置

      currentPage: 1,         // 当前页码
      currentSize: 5,         // 每页展示信息数量
      countDate: 0,           // 条件查询结果集数量
    }
  },
  methods: {

    /**
     * 业务：赋予角色
     * 按钮：提交按钮---角色列表弹窗
     */
    handleCloses() {
      let path = "http://localhost:9090/system/users/updateRoleByUserId/"+this.ruleForm.id
      let data = this.$refs.tree.getCheckedKeys()

      console.log("【为角色ID为【"+this.ruleForm.id+"】赋予角色的id：【"+data+"】")
      this.axios.post(path, data).then((response) => {
        switch (response.data.code) {
          case 200:
            this.$message({
              type: 'success',
              message: '分配角色成功!'
            });
            this.optionsSelectEcho = []
            break;
          default:
            this.$message({
              type: 'error',
              message: response.data.message
            })
            break;
        }
      })
      this.drawer = false;
      this.closeDialog();
    },


    /**
     * 业务：修改用户状态
     * @param id
     */
    handleEdit(row) {
      this.$confirm('此操作将使【'+row.username+'】的账号无法正常使用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let path = "http://localhost:9090/system/users/updateById"
        let data = {
          id: row.id,
          status: row.status
        }
        /**
         * 修改根据用户id修改用户状态
         */
        this.axios.post(path, data).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: "修改成功"
              })
              this.listUsersByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              if (row.status === 0) {
                row.status = 1;
              } else {
                row.status = 0;
              }
              break;
          }
        })
      }).catch(() => {
        if (row.status === 0) {
          row.status = 1;
        } else {
          row.status = 0;
        }
      })
    },



    /**
     * 业务：删除
     * row
     */
    handleDelete(row) {
      this.$confirm('此操作将永久删除【' + row.username + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post("http://localhost:9090/system/users/deleteById", row).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.listUsersByCondition()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              });
              break;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    /**
     * 业务：批量删除
     */
    handleDeleteList() {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'info',
          message: '请勾选需要删除的品牌'
        });
        return;
      }
      let array = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        array.push(this.multipleSelection[i].id);
      }

      this.$confirm('此操作将永久删除ID为【'+array+'】的用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post("http://localhost:9090/system/users/deleteByIds", array).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.listUsersByCondition()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection();
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        });
      });
    },



    /**
     * 业务：获取批量删除业务选中的复选框
     * @param val
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },


    /**
     * 业务：根据条件查询用户列表
     */
    listUsersByCondition() {
      /**
       * 查询满足查询条件的信息数量
       */
      this.axios.post("http://localhost:9090/system/users/getCountAll", this.input).then((response) => {
        this.countDate = response.data;
        // console.log("满足当前条件共有【"+response.data+"】条信息")

        let temp = response.data;
        if (response.data>0) {
          let tempPageNum = temp % this.currentSize ===0? temp / this.currentSize : temp / this.currentSize + 1;
          if (this.currentPage > tempPageNum) {
            this.input.pageNum = 0;
            this.currentPage = 1;
          }
          this.input.pageNum = (this.currentPage - 1) * this.currentSize;
          this.input.pageSize = this.currentSize;

          /**
           * 查询满足查询条件的用户列表
           */
          this.axios.post("http://localhost:9090/system/users/listUsersByCondition", this.input).then((response) => {
            this.tableData = response.data.list;
          })
        }else {
          this.tableData = ''
        }
      })
    },


    /**
     * 业务：回显角色列表
     */
    menuPopups() {
      this.axios.get("http://localhost:9090/system/role/getRoleEcho").then((response) => {
        console.log("用户的角色回显："+response.data)
        console.log(1)
          let newList = []; //定义一个新数组用来存放遍历的数据
          let jsonObjs = response.data
          for (let i = 0; i < jsonObjs.length; i++) {
            newList[i] = {
              key: jsonObjs[i].id,
              label: jsonObjs[i].name,
            }
          }
        this.treeData = newList;
      })
    },
    

    /**
     * 业务：回显当前用户角色
     */
    userRoleEcho(userId){
      this.ruleForm.id = userId;
      this.axios.get("http://localhost:9090/system/role/getBackFillByUserId?userId="+userId).then((response)=>{
        this.optionsSelectEcho = response.data;
        console.log("用户角色回显成功："+this.optionsSelectEcho)
      })
    },



    /**
     * 按钮：叉---权限列表弹窗
     */
    handleClose() {
      this.drawer = false;
    },


    /**
     * 按钮：取消按钮---权限列表弹窗
     */
    cancelForm() {
      this.drawer = false;
    },


    /**
     * 清空选中
     */
    clearC(){
      this.$refs.cascader.$refs.panel.clearCheckedNodes();
    },



    /**
     * 业务：页面按钮，根据选择项控制提交用户状态的条件
     */
    queryStatus(id) {
      switch (id) {
        case 1:
          this.usernameStatus = '正常使用';
          this.input.status = 1;
          break;
        case 2:
          this.usernameStatus = '禁用状态';
          this.input.status = 0;
          break;
        case 3:
          this.usernameStatus = '全部状态';
          this.input.status = null;
          break;
      }
      this.listUsersByCondition();
    },


    /**
     * 业务：获取分页，每页条数
     * @param val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentSize = val;
      this.listUsersByCondition();
    },


    /**
     * 业务：获取当前页数
     * @param val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.listUsersByCondition();
    },


    /**
     * 清除弹窗数据及遗留效果
     */
    closeDialog(ruleForm) {
      if (this.$refs[ruleForm] !== undefined) {
        this.$refs[ruleForm].resetFields();
      }
    },
  },
  created() {
    this.listUsersByCondition();
  }
}

</script>
